package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.LinkSlideAdapter;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.beans.Link;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MineAdresser extends BaseActivity implements View.OnClickListener{
    private Button adesend;
    private Button adereciver;
    private Button addlinkman;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String is="1";
    private JSONArray array;
    private HashMap map;
    private ArrayList<Link.DataBean> linkList;
    private ListView sendlist;
    private ImageView linksendback;
    private Button addressadd;
    private HashMap<String,String>maplink;
    private List<HashMap<String,String>> choose;
    private Button chooselinkbt;
    private TextView chooselinktx;
    private List<HashMap<String,String>> backList;
    private static final int ADDRESSTWO = 1002;
    private String address1;
    private String name1;
    private String id1;
    private TextView addresstext1;
    private String id;
    private float distance;
    private String slongitude;
    private String slatitude;

    private int[] dis;
    private List<HashMap<String, String>> point;
    private List<Integer> dd;
    List<Integer> linkTrue = new ArrayList();
    private List<Integer> ss;
    private HashMap<String, String> map1;
    private HashMap<String, String> item;
    private HashMap<String, String> map2;
    private List<Integer> index;
    private Handler han = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Bundle data = msg.getData();
                    List<Double> data1 = (List<Double>) data.getSerializable("data");
                    for (int i = 0; i < data1.size(); i++) {

                    }
                    break;
            }
            Intent i = new Intent();
            Bundle b = new Bundle();
            b.putSerializable("back", (Serializable) backList);
            b.putSerializable("ddd", (Serializable) ddd);
            i.putExtras(b);
            MineAdresser.this.setResult(RESULT_OK,i);
            finish();

        }
    };
    private ImageView backmain;
    private DecimalFormat df;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_adresser);
        sendlist = (ListView) findViewById(R.id.sendlistview);
        addressadd = (Button) findViewById(R.id.address_addlinkbt);
        chooselinkbt = (Button) findViewById(R.id.choose_linkbt);
        chooselinktx = (TextView) findViewById(R.id.chose_linktx);
        backmain = (ImageView) findViewById(R.id.addresser_backmain);
        addresstext1 = (TextView) findViewById(R.id.address_linktext1);
        linksendback = (ImageView) findViewById(R.id.link_send_back);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        getContact();
        df = new DecimalFormat("#.00");
        // 多选联系人的集合
        choose = new ArrayList<>();
        // 返回多选联系人的集合
        backList = new ArrayList<>();

        getLinkdata();
        linksendback.setOnClickListener(this);
        addressadd.setOnClickListener(this);
        chooselinkbt.setOnClickListener(this);
        chooselinktx.setOnClickListener(this);
        backmain.setOnClickListener(this);

    }
    // 获取默认联系人
    private void getContact() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.ONE_CONTACTLINK);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        //类型0：发件人 类型1:收件人
        object.put("type","0");
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                JSONObject obj = JSON.parseObject(result);
                String data = obj.getString("data");
                JSONObject obj1 = JSON.parseObject(data);
                String address = obj1.getString("address");
                String name = obj1.getString("name");
                String longitude = obj1.getString("longitude");
                String latitude = obj1.getString("latitude");
                String id = obj1.getString("id");

                map1 = new HashMap();
                map1.put("address",address);
                map1.put("name",name);
                map1.put("longitude",longitude);
                map1.put("latitude",latitude);
                map1.put("id",id);

                addresstext1.setText(name+" "+address);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(MineAdresser.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
       getLinkdata();
    }

    // 获取收件人信息
    private void getLinkdata() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/contact/getContactList");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject j = new JSONObject();
        j.put("type","1");
        params.addParameter("params",j.toJSONString());

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                getData(result);

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(MineAdresser.this,ex);
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }

    private void getData(String result) {
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
        String data = obj.getString("data");
        array = JSONArray.parseArray(data);
        linkList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            final Link.DataBean dataBean = new Link.DataBean();
            com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(String.valueOf(array.get(i)));
            String name = obj1.getString("name");
            String phone = obj1.getString("phone");
            String address = obj1.getString("address");
            String id = obj1.getString("id");
            String longitude = obj1.getString("longitude");
            String latitude = obj1.getString("latitude");
            dataBean.setPhone(phone);
            dataBean.setId(id);
            dataBean.setAddress(address);
            dataBean.setName(name);
            dataBean.setState(false);
            dataBean.setLatitude(latitude);
            dataBean.setLongitude(longitude);
            linkList.add(dataBean);
        }
        final LinkSlideAdapter linkSlideAdapter = new LinkSlideAdapter(MineAdresser.this,linkList);
        sendlist.setAdapter(linkSlideAdapter);
        sendlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LinkSlideAdapter.ViewHolder holder= (LinkSlideAdapter.ViewHolder) view.getTag();
                holder.itembox.toggle();
                linkSlideAdapter.linkList.get(position).setState(holder.itembox.isChecked());
            }
        });
        linkSlideAdapter.notifyDataSetChanged();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.addresser_backmain:
                startActivity(new Intent(MineAdresser.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.link_send_back:
                finish();
                break;
            case R.id.address_addlinkbt:
                Intent intent = new Intent(MineAdresser.this,AddLinkmanActivity.class);
                intent.putExtra("is",is);
                startActivity(intent);
                break;
            case R.id.choose_linkbt:
                if (map2==null){
                    if (map1==null){
                        Toast.makeText(this, "请选择发件人", Toast.LENGTH_SHORT).show();
                    }else {
                        if (linkList!=null){
                            for (int i = 0; i < linkList.size(); i++) {
                                Boolean state = linkList.get(i).getState();
                                if (state){
                                    linkTrue.add(i);
                                }
                            }
                        }else {

                        }
                        if (linkTrue.size()==0){
                            Toast.makeText(this, "请选择收系人", Toast.LENGTH_SHORT).show();
                        }else {
                            onDistacneOrder();
                        }


                    }

                }else {
                    if (linkList!=null){
                        for (int i = 0; i < linkList.size(); i++) {
                            Boolean state = linkList.get(i).getState();
                            if (state){
                                linkTrue.add(i);
                            }
                        }
                    }else {

                    }
                    if (linkTrue.size()==0){
                        Toast.makeText(this, "请选择收系人", Toast.LENGTH_SHORT).show();
                    }else {
                        onDistacneOrder();
                    }

                }

                break;
            case R.id.chose_linktx:// 获取发件人
              Intent in = new Intent(MineAdresser.this,MineServicer.class);
                startActivityForResult(in,ADDRESSTWO);
                break;
        }
    }

    private void onDistacneOrder() {
      if (map2!=null){// 如果联系人页面返回的数据不为空 添加
            backList.add(map2);
        }else { // 反之 为空就添加默认联系人
          if (map1!=null){
              backList.add(map1);
          }else {
              Toast.makeText(this, "请选择发件人", Toast.LENGTH_SHORT).show();
          }

        }
        if (linkList!=null){
            for (int i = 0; i < linkList.size(); i++) {
                Boolean state = linkList.get(i).getState();
                if (state){
                    Link.DataBean item = linkList.get(i);
                    maplink = new HashMap<String, String>();
                    maplink.put("address",item.getAddress());
                    maplink.put("name",item.getName());
                    maplink.put("phone",item.getPhone());
                    maplink.put("id",item.getId());
                    maplink.put("latitude",item.getLatitude());
                    maplink.put("longitude",item.getLongitude());
                    maplink.put("state",String.valueOf(item.getState()));
                   backList.add(maplink);

                }
            }
        }else {
            Toast.makeText(this, "请选择收系人", Toast.LENGTH_SHORT).show();
        }
        // 排序后d
        // 保存测距后的距离
        //backList 经纬度的集合 测距用
        // 保存起点的集合
        point = new ArrayList();
            // 此处测距没两点之间的距离
        for (int j = 0; j < backList.size(); j++) {
            dd = new ArrayList<>();
            index = new ArrayList<>();
            HashMap<String,String> map4;
            ss = new ArrayList<>();
            point.add(backList.get(j));
            if (j==backList.size()-1){
                break;
            }
            // 双层循环 取出list的元素
            for (int i = 0; i < backList.size(); i++) {
                // 测直线距离
                LatLng slatLng;
                   if (i!=j&i>j){
                       // 起点坐标
                       Double latitude = Double.valueOf(backList.get(i).get("latitude"));
                       Double longitude = Double.valueOf(backList.get(i).get("longitude"));
                       slatLng = new LatLng(Double.valueOf(backList.get(j).get("latitude")),Double.valueOf(backList.get(j).get("longitude")));
                       // 终点坐标
                       LatLng elatLng = new LatLng(latitude,longitude);
                       float v = AMapUtils.calculateLineDistance(slatLng, elatLng);
                       // 保存最小距离
                       dd.add((int) v);
                       // 保存相对元素索引
                       index.add(i);
                   }
            }
            // 保存结果索引 方便找出最小距离经纬度
            List<Integer> cc = new ArrayList<>();
            for (int f = 0; f < dd.size(); f++) {
                cc.add(dd.get(f));
            }
            // 排序
            int t;
            for (int a = 0; a < dd.size()-1; a++) {
                //  比较距离
                for (int b = 0; b < dd.size()-a-1; b++) {
                    if (dd.get(b)> dd.get(b+1)){
                        t= dd.get(b);
                        dd.set(b, dd.get(b+1));
                        dd.set(b+1, t);
                    }
                }
            }
            // 把最小距离保存到ss中
            for (int d = 0; d < dd.size(); d++) {

                if (d==0){
                    ss.add(dd.get(d));
                }
            }

            for (int i = 0; i < cc.size(); i++) {
                if (ss.get(0)==cc.get(i)){
                   if (backList.get(index.get(i)).get("id").equals(backList.get(j+1).get("id"))==false){
                       map4 = backList.get(j+1);
                        backList.set(j+1,backList.get(index.get(i)));
                       backList.set(index.get(i),map4);
                    }
                }
            }
        }
        // 测距
        for (int i = 0; i < point.size(); i++) {
            if (i==point.size()-1){
                break;
            }
                    Double slat = Double.valueOf(point.get(i).get("latitude"));
                    Double slon = Double.valueOf(point.get(i).get("longitude"));
                    Double elat = Double.valueOf(point.get(i+1).get("latitude"));
                    Double elon = Double.valueOf(point.get(i+1).get("longitude"));
                    LatLonPoint s = new LatLonPoint(slat,slon);
                    LatLonPoint e = new LatLonPoint(elat,elon);

                     getDispatching(s,e);
        }
    }
    List<Double> ddd = new ArrayList<>();

    // 测距
   private void getDispatching(LatLonPoint a ,LatLonPoint b) {

        RouteSearch search = new RouteSearch(MineAdresser.this);
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(a,b);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,RouteSearch.DrivingShortDistance,null,null,"");


       search.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                // 拿结果
                List<DrivePath> paths = driveRouteResult.getPaths();
                for (int i1 = 0; i1 < paths.size(); i1++) {
                    distance = paths.get(i1).getDistance();
                }
                ddd.add(Double.valueOf(df.format(distance)) );
                if (ddd.size()==point.size()-1){
                    Message m = new Message();
                    m.what=1;
                    Bundle b = new Bundle();
                    b.putSerializable("data", (Serializable) ddd);
                    m.setData(b);
                    han.sendMessage(m);
                }

            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });

        search.calculateDriveRouteAsyn(query);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK){
            Bundle bd = data.getExtras();
            // 添加进集合
            String address = (String) bd.get("address1");
            String phone = (String) bd.get("phone1");
            String name = (String) bd.get("name1");
            String id = (String) bd.get("id");
            String longitude = (String) bd.get("longitude");
            String latitude = (String) bd.get("latitude");
            map2 = new HashMap();
            map2.put("address",address);
            map2.put("phone",phone);
            map2.put("name",name);
            map2.put("id",id);
            map2.put("longitude",longitude);
            map2.put("latitude",latitude);

            addresstext1.setText(name+" "+address);
        }

    }

}
